/*
 * JGrass - Free Open Source Java GIS http://www.jgrass.org 
 * (C) HydroloGIS - www.hydrologis.com 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package eu.hydrologis.jgrass.ui.actions;

import java.io.File;
import java.util.List;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.preferences.ScopedPreferenceStore;

import eu.hydrologis.jgrass.console.editor.ConsoleEditorPlugin;
import eu.hydrologis.jgrass.console.editor.preferences.PreferencesInitializer;
import eu.hydrologis.jgrass.grass.GrassPlugin;
import eu.hydrologis.jgrass.ui.utilities.CatalogJGrassMapsetTreeViewerDialog;
import eu.hydrologis.jgrass.uibuilder.jgrassdependent.utils.UIBuilderActionSupporter;
import eu.udig.catalog.jgrass.core.JGrassMapsetGeoResource;

/**
 * this class was generated by JGrass's createCommands script
 */
public class g_setmapset extends UIBuilderActionSupporter implements IWorkbenchWindowActionDelegate {

    private IWorkbenchWindow window;
    private String mapset;

    public void dispose() {
    }

    public void init( IWorkbenchWindow window ) {
        this.window = window;
    }

    public void run( IAction action ) {

        final ScopedPreferenceStore m_preferences = (ScopedPreferenceStore) ConsoleEditorPlugin
                .getDefault().getPreferenceStore();

        Dialog dialog = new Dialog(window.getShell()){

            private Text text;

            protected Control createDialogArea( Composite parent ) {
                Composite composite = (Composite) super.createDialogArea(parent);
                composite.setLayout(new GridLayout(4, false));

                Label label = new Label(composite, SWT.NONE);
                label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
                label.setText("mapset path");

                mapset = m_preferences.getString(PreferencesInitializer.CONSOLE_ARGV_MAPSET);
                if (mapset != null) {
                    File f = new File(mapset);
                    if (!f.exists()) {
                        mapset = "";
                    }
                }
                text = new Text(composite, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
                text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
                text.setText(mapset);

                final Button mapsetSelectionButton = new Button(composite, SWT.PUSH);
                mapsetSelectionButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
                        false));
                mapsetSelectionButton.setToolTipText("Select a mapset from the catalog.");
                mapsetSelectionButton.setText("catalog");
                mapsetSelectionButton
                        .addSelectionListener(new org.eclipse.swt.events.SelectionAdapter(){
                            public void widgetSelected( org.eclipse.swt.events.SelectionEvent e ) {

                                CatalogJGrassMapsetTreeViewerDialog cDialog = new CatalogJGrassMapsetTreeViewerDialog();
                                cDialog.open(mapsetSelectionButton.getShell());
                                List<JGrassMapsetGeoResource> selectedLayers = cDialog
                                        .getSelectedLayers();
                                if (selectedLayers == null || selectedLayers.size() == 0) {
                                    return;
                                }
                                JGrassMapsetGeoResource grassMapsetGeoResource = selectedLayers
                                        .get(0);
                                File mapsetFile = grassMapsetGeoResource.getFile();
                                if (mapsetFile.exists()
                                        && GrassPlugin.getDefault().isMapsetConsistent(
                                                mapsetFile.getAbsolutePath())) {
                                    text.setText(mapsetFile.getAbsolutePath());
                                } else {
                                    String msg = "This is not a valid GRASS mapset folder. Please supply a valid mapset folder.";
                                    popupError(msg);
                                }
                            }

                        });

                Button browseButton = new Button(composite, SWT.PUSH);
                browseButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
                browseButton.setText("...");
                browseButton.setToolTipText("Browse the filesystem for a mapset folder.");
                browseButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter(){
                    public void widgetSelected( org.eclipse.swt.events.SelectionEvent e ) {
                        DirectoryDialog fileDialog = new DirectoryDialog(window.getShell(),
                                SWT.OPEN);
                        String path = fileDialog.open();
                        if (path != null) {
                            File f = new File(path);
                            if (f.exists() && GrassPlugin.getDefault().isMapsetConsistent(path)) {
                                text.setText(f.getAbsolutePath());
                            } else {
                                String msg = "This is not a valid GRASS mapset folder. Please supply a valid mapset folder.";
                                popupError(msg);
                            }
                        }
                    }

                });

                return composite;
            }

            protected void configureShell( Shell shell ) {
                super.configureShell(shell);
                shell.setText("g.setmapset");
                shell.setSize(new Point(450, 120));

                Shell mainshell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
                Rectangle bounds = mainshell.getBounds();
                Rectangle rect = shell.getBounds();
                int x = bounds.x + (bounds.width - rect.width) / 2;
                int y = bounds.y + (bounds.height - rect.height) / 2;
                shell.setLocation(x, y);
            }

            protected void okPressed() {
                m_preferences.setValue(PreferencesInitializer.CONSOLE_ARGV_MAPSET, text.getText());
                super.okPressed();
            }

        };

        dialog.setBlockOnOpen(true);
        dialog.open();
    }

    private void popupError( String msg ) {
        MessageBox msgBox = new MessageBox(window.getShell(), SWT.ICON_ERROR);
        msgBox.setMessage(msg);
        msgBox.open();
    }

    public void selectionChanged( IAction action, ISelection selection ) {
    }
}
